/*
Copyright 2017 yangchong211（github.com/yangchong211）

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.yc.video.ui.pip;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.RoundProgressBar;
import ohos.agp.components.StackLayout;
import ohos.app.Context;

import com.yc.video.ResourceTable;
import com.yc.video.bridge.ControlWrapper;
import com.yc.video.config.ConstantKeys;
import com.yc.video.player.VideoViewManager;
import com.yc.video.ui.view.InterControlView;

/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211
 *     time  : 2017/11/9
 *     desc  : 悬浮窗视图
 *     revise:
 * </pre>
 */
public class CustomFloatView extends StackLayout implements InterControlView, Component.ClickedListener {
    private ControlWrapper mControlWrapper;
    private Context mContext;
    private Image mIvStartPlay;
    private RoundProgressBar mPbLoading;
    private Image mIvClose;
    private Image mIvSkip;
    private ProgressBar mPbBottomProgress;
    private boolean mIsShowBottomProgress = true;

    public CustomFloatView(Context context) {
        super(context);
        init(context);
    }

    public CustomFloatView(Context context, AttrSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomFloatView(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        Component view = LayoutScatter.getInstance(getContext()).parse(
            ResourceTable.Layout_custom_video_player_float, this, true);
        initFindViewById(view);
        initListener();
    }

    private void initFindViewById(Component view) {
        mIvStartPlay = (Image) view.findComponentById(ResourceTable.Id_iv_start_play);
        mPbLoading = (RoundProgressBar) view.findComponentById(ResourceTable.Id_pb_loading);
        mIvClose = (Image) view.findComponentById(ResourceTable.Id_iv_close);
        mIvSkip = (Image) view.findComponentById(ResourceTable.Id_iv_skip);
        mPbBottomProgress = (ProgressBar) view.findComponentById(ResourceTable.Id_pb_bottom_progress);
        mIvClose.setVisibility(Component.HIDE);
        mIvSkip.setVisibility(Component.HIDE);
    }

    private void initListener() {
        mIvStartPlay.setClickedListener(this);
        mIvClose.setClickedListener(this);
        mIvSkip.setClickedListener(this);
    }

    @Override
    public void onClick(Component v) {
        if (v == mIvClose) {
            FloatVideoManager.getInstance(mContext).stopFloatWindow();
            FloatVideoManager.getInstance(mContext).reset();
        } else if (v == mIvStartPlay) {
            mControlWrapper.togglePlay();
        } else if (v == mIvSkip) {
            if (FloatVideoManager.getInstance(mContext).getActClass() != null) {
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ABILITY_NEW_MISSION);
                Operation operation = new Intent.OperationBuilder()
                    .withAbilityName(FloatVideoManager.getInstance(mContext).getActClass())
                    .build();
                intent.setOperation(operation);
                ((AbilitySlice) getContext()).startAbility(intent);
            }
        }
    }

    @Override
    public void attach(ControlWrapper controlWrapper) {
        mControlWrapper = controlWrapper;
    }

    @Override
    public Component getView() {
        return this;
    }

    @Override
    public void onVisibilityChanged(boolean isVisible, Animator anim) {
        if (isVisible) {
            if (mIvStartPlay.getVisibility() == VISIBLE) {
                return;
            }
            mIvStartPlay.setVisibility(VISIBLE);
            anim.start();
            if (mIsShowBottomProgress) {
                mPbBottomProgress.setVisibility(HIDE);
            }
        } else {
            if (mIvStartPlay.getVisibility() == HIDE) {
                return;
            }
            mIvStartPlay.setVisibility(HIDE);
            anim.start();
            if (mIsShowBottomProgress) {
                mPbBottomProgress.setVisibility(VISIBLE);
                AnimatorProperty animatorProperty = mPbBottomProgress.createAnimatorProperty();
                animatorProperty.alpha(1).alphaFrom(0).setDuration(300);
                animatorProperty.start();
            }
        }
    }

    @Override
    public void onPlayStateChanged(int playState) {
        switch (playState) {
            case ConstantKeys.CurrentState.STATE_IDLE:
                mIvStartPlay.setSelected(false);
                mIvStartPlay.setVisibility(VISIBLE);
                mPbLoading.setVisibility(HIDE);
                break;
            case ConstantKeys.CurrentState.STATE_PLAYING:
                mIvStartPlay.setSelected(true);
                mIvStartPlay.setVisibility(HIDE);
                mPbLoading.setVisibility(HIDE);
                if (mIsShowBottomProgress) {
                    if (mControlWrapper.isShowing()) {
                        mPbBottomProgress.setVisibility(HIDE);
                    } else {
                        mPbBottomProgress.setVisibility(VISIBLE);
                    }
                }
                // 开始刷新进度
                mControlWrapper.startProgress();
                break;
            case ConstantKeys.CurrentState.STATE_PAUSED:
                mIvStartPlay.setSelected(false);
                mIvStartPlay.setVisibility(VISIBLE);
                mPbLoading.setVisibility(HIDE);
                break;
            case ConstantKeys.CurrentState.STATE_PREPARING:
                mIvStartPlay.setVisibility(HIDE);
                mIvStartPlay.setVisibility(VISIBLE);
                break;
            case ConstantKeys.CurrentState.STATE_PREPARED:
                mIvStartPlay.setVisibility(HIDE);
                mPbLoading.setVisibility(HIDE);
                break;
            case ConstantKeys.CurrentState.STATE_ERROR:
                mPbLoading.setVisibility(HIDE);
                mIvStartPlay.setVisibility(HIDE);
                moveChildToFront(this);
                break;
            case ConstantKeys.CurrentState.STATE_BUFFERING_PAUSED:
                mIvStartPlay.setVisibility(HIDE);
                mPbLoading.setVisibility(VISIBLE);
                break;
            case ConstantKeys.CurrentState.STATE_COMPLETED:
                mIvStartPlay.setVisibility(HIDE);
                mPbLoading.setVisibility(HIDE);
                mIvStartPlay.setSelected(mControlWrapper.isPlaying());
                break;
            case ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING:
                moveChildToFront(this);
                mPbBottomProgress.setProgressValue(0);
                mPbBottomProgress.setViceProgress(0);
                break;
            case ConstantKeys.CurrentState.STATE_START_ABORT:
                VideoViewManager.instance().setPlayOnMobileNetwork(true);
                mControlWrapper.start();
                break;
        }
    }

    @Override
    public void onPlayerStateChanged(int playerState) {

    }

    @Override
    public void setProgress(int duration, int position) {
        if (duration > 0) {
            int pos = (int) (position * 1.0 / duration * mPbBottomProgress.getMax());
            mPbBottomProgress.setProgressValue(pos);
        }
        int percent = mControlWrapper.getBufferedPercentage();
        if (percent >= 95) {
            // 解决缓冲进度不能100%问题
            mPbBottomProgress.setViceProgress(mPbBottomProgress.getMax());
        } else {
            mPbBottomProgress.setViceProgress(percent * 10);
        }
    }

    @Override
    public void onLockStateChanged(boolean isLocked) {
    }
}
